package com.mobile.collect.activitys;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.mobile.collect.R;
import com.mobile.collect.beans.DevicePicInfo;
import com.mobile.collect.db.EntityManager;
import com.mobile.collect.dialogs.BottomListDialog;
import com.mobile.collect.dialogs.v3.TipDialog;
import com.mobile.collect.present.AddDeviceUnitPresent;
import com.mobile.collect.utils.AppContents;
import com.mobile.collect.utils.TakePicUtils;
import com.mobile.collect.view.InputDialog;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.model.TResult;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.mvp.XActivity;

public class AddDeviceUnitActivity extends XActivity<AddDeviceUnitPresent> implements TakePhoto.TakeResultListener {

    @BindView(R.id.edit_unitName)
    TextView editUnitName;
    @BindView(R.id.edit_main_reference)
    TextView editMainReference;
    @BindView(R.id.deviceNameEt)
    EditText deviceNameEt;
    @BindView(R.id.edit_main_tag)
    TextView editMainTag;
    @BindView(R.id.edit_direction)
    TextView editDirection;
    @BindView(R.id.edit_floor)
    TextView editFloor;
    @BindView(R.id.statusTv)
    TextView statusTv;
    @BindView(R.id.distanceEt)
    TextView distanceEt;
    @BindView(R.id.picNoTv)
    TextView picNoTv;
    @BindView(R.id.addPicIv)
    ImageView addPicIv;
    @BindView(R.id.rightIv)
    ImageView rightIv;
    @BindView(R.id.scrollViewLayout)
    NestedScrollView scrollViewLayout;

    TakePicUtils takePicUtils;
    private Long deviceDbId;
    private Long picDbId;
    String folderPath;
    //    String picPath;
    String deviceName;
    //    boolean isUpdate;
    int operateType;// 0新增 1 修改 2 插入
    DevicePicInfo newPicInfo;
    private String mLabel;
    private int insertIndex;

    @Override
    public void initView() {
        super.initView();
        switch (operateType) {
            case 0:
                titleTv.setText("新增");
                break;
            case 1:
                titleTv.setText("修改");
                rightIv.setVisibility(View.INVISIBLE);
                break;
            case 2:
                titleTv.setText("插入");
                break;
        }
        initTextView();
//        if (isUpdate) {
//            rightIv.setVisibility(View.INVISIBLE);
//        }
    }

    private void setDefault() {
        if (null != newPicInfo) {
            editUnitName.setText(newPicInfo.getUnitName());
            editMainReference.setText(newPicInfo.getReference());
            editDirection.setText(newPicInfo.getDirection());
            editFloor.setText(newPicInfo.getFloor());
            deviceNameEt.setText(newPicInfo.getDeviceName());
            distanceEt.setText(newPicInfo.getDistance());
            picNoTv.setText(newPicInfo.getPicNo());
            if (operateType == 0) {//新增
                setLableIndex();
            } else if (operateType == 1) {//修改
                mLabel = newPicInfo.getLabel();
                editMainTag.setText(newPicInfo.getLabel());
                Glide.with(context).load(newPicInfo.getPicPath()).diskCacheStrategy(DiskCacheStrategy.ALL).into(addPicIv);
            } else if (operateType == 2) {//插入
                mLabel = newPicInfo.getLabel();
                String label = newPicInfo.getLabel();
                Integer nexIndex = Integer.parseInt(label) + 1;
                editMainTag.setText(getP().getIndex(nexIndex));
            }
        }
    }


    private void setLableIndex() {
        DevicePicInfo lastPIcInfo = EntityManager.getInstance().queryLastDeviceUnitByName(deviceDbId, editUnitName.getText().toString());
        int nexIndex = 1;
        if (null != lastPIcInfo) {
            nexIndex = Integer.parseInt(lastPIcInfo.getLabel()) + 1;
        }
        mLabel = getP().getIndex(nexIndex);
        editMainTag.setText(mLabel);
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        folderPath = AppContents.galleryPath + "/" + deviceName;
        File file = new File(folderPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        takePicUtils = new TakePicUtils(this, this);

        if (picDbId != -1) {
            newPicInfo = EntityManager.getInstance().queryDevicePicIById(picDbId);
            if (operateType == 0 || operateType == 2) {
                newPicInfo.setPicPath("");
                newPicInfo.set_ID(null);
            }
        } else {
            newPicInfo = new DevicePicInfo();
            newPicInfo.setParentId(deviceDbId);
        }
        setDefault();
    }


    @Override
    public void getDataFromServer() {

    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_adddeviceunit;
    }

    @Override
    public void getIntentData() {
        picDbId = getIntent().getLongExtra("picdbid", -1);
        deviceDbId = getIntent().getLongExtra("devicedbid", -1);
        deviceName = getIntent().getStringExtra("devicename");
        operateType = getIntent().getIntExtra("operateType", 0);
        insertIndex = getIntent().getIntExtra("insertIndex", 0);
    }

    @Override
    public AddDeviceUnitPresent newP() {
        return new AddDeviceUnitPresent();
    }

    @OnClick({R.id.addPicIv, R.id.btn_add, R.id.edit_unitName, R.id.edit_main_tag, R.id.edit_main_reference, R.id.edit_floor, R.id.distanceEt, R.id.picNoTv,
            R.id.clearDeviceNameIv, R.id.clearunitIv, R.id.clearreferenceIv, R.id.clearretagIv, R.id.clearfloorIv, R.id.edit_direction, R.id.statusTv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.clearunitIv:
                editUnitName.setText("");
                break;
            case R.id.clearfloorIv:
                editFloor.setText("");
                break;
            case R.id.clearreferenceIv:
                editMainReference.setText("");
                break;
            case R.id.clearretagIv:
//                editMainTag.setText("");
                break;
            case R.id.clearDeviceNameIv:
                deviceNameEt.setText("");
                break;
            case R.id.edit_direction:
                showDirection();
                break;
            case R.id.statusTv:
//                showStatus();
                break;
            case R.id.addPicIv:
                showPhotoBottomDialog();
                break;
            case R.id.btn_add:
                savePicInfo();
                break;
            case R.id.edit_main_reference:
//                showKeyBroad(editMainReference, "参考物");
                showBroadPop("参考物", InputDialog.broad3, 0, new InputDialog.InputCompleteListener() {
                    @Override
                    public void onInputComplete(String value) {
                        editMainReference.setText(value);
                        deviceNameEt.setText(value);
                    }
                });

                break;
            case R.id.edit_floor:
//                showFloorPop("楼层", editFloor);
                showBroadPop("楼层", 0, editFloor, InputDialog.broad5);
                break;
            case R.id.distanceEt:
                showBroadPop("距离", 0, distanceEt, InputDialog.broad2);
//                showNumberDialog("距离", distanceEt, 0, false);
                break;
            case R.id.edit_unitName:
                showBroadPop("单元名称", InputDialog.broad0, 4, new InputDialog.InputCompleteListener() {
                    @Override
                    public void onInputComplete(String value) {
                        editUnitName.setText(value);
                        setLableIndex();
                    }
                });
//                showUnitNameDialog("单元名称", editUnitName, 4, true);
                break;
            case R.id.edit_main_tag:
//                showBroadPop("标签号",4,editMainTag,InputDialog.broad1);
                break;
            case R.id.picNoTv:
                showBroadPop("图号", 0, picNoTv, InputDialog.broad1);
                break;

        }
    }


    private void showDirection() {
        List<String> list = new ArrayList<>();
        list.add("东");
        list.add("南");
        list.add("西");
        list.add("北");
        list.add("东北");
        list.add("西北");
        list.add("东南");
        list.add("西南");
        list.add("顶部");
        list.add("底部");
        list.add("下方");
        list.add("上方");
        showBottomDialog(editDirection, list);
    }

    private void savePicInfo() {
        String unitName = editUnitName.getText().toString();
        String mainReference = editMainReference.getText().toString();
//        String label = editMainTag.getText().toString();
        String direction = editDirection.getText().toString();
        String floor = editFloor.getText().toString();
        String deviceName = deviceNameEt.getText().toString();
        String distance = distanceEt.getText().toString();
        String picNo = picNoTv.getText().toString();


        if (isNull(unitName)) {
            TipDialog.show(this, "单元名称不能为空", TipDialog.TYPE.WARNING);
            return;
        }
        if (isNull(mainReference)) {
            TipDialog.show(this, "主要参考物不能为空", TipDialog.TYPE.WARNING);
            return;
        }
        if (isNull(deviceName)) {
            TipDialog.show(this, "设备名称不能为空", TipDialog.TYPE.WARNING);
            return;
        }
        if (isNull(picNo)) {
            picNo = "NA";
        }
        if (isNull(direction)) {
            TipDialog.show(this, "方向不能为空", TipDialog.TYPE.WARNING);
            return;
        }
        if (isNull(floor)) {
            TipDialog.show(this, "楼层不能为空", TipDialog.TYPE.WARNING);
            return;
        }
        if (isNull(distance)) {
            TipDialog.show(this, "距离不能为空", TipDialog.TYPE.WARNING);
            return;
        }
        if (TextUtils.isEmpty(newPicInfo.getPicPath())) {
            if (TextUtils.isEmpty(newPicInfo.getPicPath())) {
                TipDialog.show(this, "请添加图片", TipDialog.TYPE.WARNING);
                return;
            }
        }


        newPicInfo.setUnitName(unitName);
        newPicInfo.setReference(mainReference);
        newPicInfo.setLabel(mLabel);
        newPicInfo.setDirection(direction);
        newPicInfo.setFloor(floor);
        newPicInfo.setDeviceName(deviceName);
        newPicInfo.setDistance(distance);
        newPicInfo.setPicNo(picNo);
        newPicInfo.setLableIsRepeat(false);
        newPicInfo.setCreateTime(Calendar.getInstance().getTimeInMillis());
        newPicInfo.setPointCount(0);
        newPicInfo.setSortIndex(insertIndex);

        if (operateType == 2) {
            List<DevicePicInfo> list =  EntityManager.getInstance().queryAllDevicePic(deviceDbId,insertIndex-1);
            for (DevicePicInfo devicePicInfo : list) {
                devicePicInfo.setSortIndex(devicePicInfo.getSortIndex()+1);
                String label = devicePicInfo.getLabel();
                int newLable = Integer.parseInt(label)+1;
                devicePicInfo.setLabel(getP().getIndex(newLable));
            }
            EntityManager.getInstance().saveDevicePicInfo(list);
        }

        long dbId = EntityManager.getInstance().saveDevicePicInfo(newPicInfo);
        TipDialog.show(AddDeviceUnitActivity.this, "添加成功", TipDialog.TYPE.SUCCESS);
        DevicePointsActivity.lunch(this, newPicInfo.getPicPath(), dbId);
        setResult(Activity.RESULT_OK);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }

        if (requestCode == 0x002) {
            String path = data.getStringExtra("picPath");
            zoom(path);
        } else {
            takePicUtils.getTakePhoto().onActivityResult(requestCode, resultCode, data);

        }
    }

    @Override
    public void takeSuccess(TResult result) {
        String newPath = result.getImage().getOriginalPath();
        zoom(newPath);
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }

    public static void lunch(Activity context, String deviceName, Long deviceDbId, int operateType, Long picDbId,int insertIndex) {
        Intent intent = new Intent(context, AddDeviceUnitActivity.class);
        intent.putExtra("devicename", deviceName);
        intent.putExtra("devicedbid", deviceDbId);
        intent.putExtra("operateType", operateType);
        intent.putExtra("picdbid", picDbId);
        intent.putExtra("insertIndex", insertIndex);
        context.startActivityForResult(intent, 0x001);
    }


    protected void showBottomDialog(final TextView view, List<String> dicList) {
        BottomListDialog bottomListDialog = new BottomListDialog(this, new BottomListDialog.BottomListSelectListener() {
            @Override
            public void itemClickCallback(String selectStr) {
                view.setText(selectStr);
            }
        });
        bottomListDialog.disPlay(dicList);
    }

    protected void showPhotoBottomDialog() {
//        startActivityForResult(new Intent(this, SquareGLSurfaceViewActivity.class), 0x002);
        List<String> list = new ArrayList<>();
        list.add("拍照");
        list.add("相册");
        BottomListDialog bottomListDialog = new BottomListDialog(this, new BottomListDialog.BottomListSelectListener() {
            @Override
            public void itemClickCallback(String selectStr) {
                if (selectStr.equals("拍照")) {
//                    startActivityForResult(new Intent(AddDeviceUnitActivity.this, SquareGLSurfaceViewActivity.class), 0x002);
                    takePicUtils.takePhotoFromCapture();
                } else {
                    takePicUtils.onPickFromGallery();
                }
            }
        });
        bottomListDialog.disPlay(list);
    }

    @Override
    public int getTitleLayoutResId() {
        return 0;
    }


    private void zoom(final String oldPath) {
        Tiny.FileCompressOptions options = new Tiny.FileCompressOptions();
        Tiny.getInstance().source(oldPath).asFile().withOptions(options).compress(new FileCallback() {
            @Override
            public void callback(boolean isSuccess, String outfile) {
                if (isSuccess) {
                    loadPic(outfile);
                } else {
                    TipDialog.show(AddDeviceUnitActivity.this, "请重新选择图片", TipDialog.TYPE.WARNING);
                }
            }
        });
    }


    private void loadPic(String outfile) {
        newPicInfo.setPicPath(outfile);
        Glide.with(context).load(outfile).asBitmap().into(addPicIv);
    }

    @Override
    public boolean isNotWorkConnect() {
        return false;
    }


    private void showKeyBroad(final TextView clickView, String label) {
//        String oldTxt = editMainReference.getText().toString();
//        KeyBroadPop numberPop = new KeyBroadPop(this, clickView, label, oldTxt, new InputDialog.InputCompleteListener() {
//            @Override
//            public void onInputComplete(String value) {
//                clickView.setText(value);
//                deviceNameEt.setText(value);
//            }
//        }, 0);
//        numberPop.show();
        showBroadPop(label, InputDialog.broad3, 0, new InputDialog.InputCompleteListener() {
            @Override
            public void onInputComplete(String value) {
                clickView.setText(value);
                deviceNameEt.setText(value);
            }
        });
    }


    private void showNumberDialog(String label, final TextView clickView, int maxCount, boolean onlyNum) {
//        NumberPop numberPop = new NumberPop(this, label, clickView.getText().toString(), new InputDialog.InputCompleteListener() {
//            @Override
//            public void onInputComplete(String value) {
//                clickView.setText(value);
//            }
//        }, maxCount);
//        numberPop.show();
//        showBroadPop(label,clickView,InputDialog.broad5);

//        showBroadPop(label,clickView,InputDialog.broad1);
    }

    private void showUnitNameDialog(String label, final TextView clickView, int maxCount, boolean onlyNum) {
//        NumberPop numberPop = new NumberPop(this, label, clickView.getText().toString(), new InputDialog.InputCompleteListener() {
//            @Override
//            public void onInputComplete(String value) {
//                clickView.setText(value);
//                setLableIndex();
//            }
//        }, maxCount);
//        numberPop.show();

        showBroadPop(label, InputDialog.broad1, maxCount, new InputDialog.InputCompleteListener() {
            @Override
            public void onInputComplete(String value) {
                clickView.setText(value);
                setLableIndex();
            }
        });
    }

    private void showFloorPop(String label, final TextView clickView) {
//        InputDialog inputDialog = new InputDialog(this, label, new InputDialog.InputCompleteListener() {
//            @Override
//            public void onInputComplete(String value) {
//                clickView.setText(value);
//            }
//        }, 0);
//        inputDialog.disPlay(InputDialog.broad5);
        showBroadPop(label, 0, clickView, InputDialog.broad5);
    }

    private void showBroadPop(String label, int maxCount, final TextView clickView, String[] paramers) {
        showBroadPop(label, paramers, maxCount, new InputDialog.InputCompleteListener() {
            @Override
            public void onInputComplete(String value) {
                clickView.setText(value);
            }
        });
    }

    private void showBroadPop(String label, String[] paramers, int maxCount, InputDialog.InputCompleteListener listener) {
        InputDialog inputDialog = new InputDialog(this, label, listener, maxCount);
        inputDialog.disPlay(paramers);
    }


    private void initTextView() {
        editMainReference.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                context.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

                int currentVersion = android.os.Build.VERSION.SDK_INT;
                String methodName = null;
                if (currentVersion >= 16) {
                    methodName = "setShowSoftInputOnFocus";
                } else if (currentVersion >= 14) {
                    methodName = "setSoftInputShownOnFocus";
                }
                if (methodName == null) {
                    editMainReference.setInputType(InputType.TYPE_NULL);
                } else {
                    Class cls = EditText.class;
                    Method setShowSoftInputOnFocus;
                    try {
                        setShowSoftInputOnFocus = cls.getMethod(methodName, boolean.class);
                        setShowSoftInputOnFocus.setAccessible(true);
                        setShowSoftInputOnFocus.invoke(editMainReference, false);
                    } catch (NoSuchMethodException e) {
                        editMainReference.setInputType(InputType.TYPE_NULL);
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
        });
    }


}
